//
//  File.swift
//
//
//  Created by didi on 2022/9/14.
//

import Fluent
import Molecular
import MolecularRedirectObjects
import Vapor

struct RedirectRuleAdminController: AdminController {
    typealias ApiModel = Redirect.Rule
    typealias DatabaseModel = RedirectRuleModel

    typealias CreateContext = RedirectRuleEditor
    typealias UpdateModelEditor = RedirectRuleEditor

    var listConfig: ListConfiguration {
        .init(allowedOrders: [
            "source",
            "destination",
        ], defaultSort: .desc)
    }

    func listSearch(_ term: String) -> [ModelValueFilter<DatabaseModel>] {
        [
            \.$source ~~ term,
        ]
    }

    func listColumns() -> [ColumnContext] {
        [
            .init("source"),
            .init("destination"),
            .init("statusCode"),
        ]
    }

    func listCells(for model: DatabaseModel) -> [CellContext] {
        [
            .init(model.source),
            .init(model.destination),
            .init(String(model.statusCode)),
        ]
    }

    func detailFields(for model: DatabaseModel) -> [DetailContext] {
        [
            .init("id", model.uuid.string),
            .init("source", model.source, label: "Source path"),
            .init("destination", model.destination, label: "Destination URL or path"),
            .init("statusCode", String(model.statusCode), label: "HTTP status code"),
            .init("notes", model.notes),
        ]
    }

    func deleteInfo(_ model: RedirectRuleModel) -> String {
        model.source
    }
}
